package com.heimo.agentlicence.ui.fragment;

import java.util.List;

import org.apache.http.NameValuePair;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.heimo.agentlicence.R;
import com.heimo.agentlicence.ui.adaptor.ScreenSlidePagerAdapter;

public class CheckDisciplineWebFragment extends BasicFragment {
	private final String TAG = "CheckDisciplineWebFragment";
	private List<NameValuePair> nvps;
	private WebView webView = null;
	private String url = "http://www.eaa.org.hk/DisciplinaryProceedings/DisciplinaryRecordsSearch/tabid/659/language/zh-HK/Default.aspx";

	public static CheckDisciplineWebFragment newInstance(Context ctx,
			ScreenSlidePagerAdapter adp) {
		CheckDisciplineWebFragment f = new CheckDisciplineWebFragment();
		f.setContext(ctx);
		f.setAdapter(adp);
		return f;
	}

	private void init() {
		webView = (WebView) v.findViewById(R.id.webView);
		// webView.setWebViewClient(new WebViewClient());

		fnSetWebClient(webView);

		// webView settings
		WebSettings webSettings = webView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setLoadWithOverviewMode(true);
		webSettings.setUseWideViewPort(true);
		webSettings.setSupportZoom(true);
		webSettings.setBuiltInZoomControls(true);

		webView.loadUrl(url);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		v = (ViewGroup) inflater.inflate(
				R.layout.activity_check_discipline_web, container, false);
		init();
		return v;
	}

	public void fnPageLoad() {
		if (this.licenceNo == null) {
			return;
		}
		Log.d(TAG, "fnLoadPage() - Start");
		fnSubmitWebView(webView);

	}

	private void fnSubmitWebView(WebView view) {
		if (licenceNo != null) {
			view.loadUrl("javascript:document.getElementById('dnn_ctr1142_ViewEAALicenceSearch_txtLicenceNo').value = '"
					+ licenceNo + "';");
			view.loadUrl("javascript:document.getElementById('dnn_ctr1142_ViewEAALicenceSearch_btnDisSearch').click();");
		}
	}

	private void fnSetWebClient(WebView webView) {
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view,
					String urlNewString) {
				view.loadUrl(urlNewString);
				return true;
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				fnSubmitWebView(view);
			}
		});
	}

}
